<?php
class Mozg_Config {
	
	protected $_config = array();
	protected $_path = '';

	protected static $_instances = array();
	
	public static function GetInstance($path, $className = false)
	{
		if (!$className) $className = __CLASS__;
		
		//optimization
		if (isset(self::$_instances[$path]) && (self::$_instances[$path] instanceof $className))
		{
			return self::$_instances[$path];
		}
		
		$path = self::NicePath($path);
		
		if (!isset(self::$_instances[$path]) || !(self::$_instances[$path] instanceof $className))
		{
			self::$_instances[$path] = new $className($path);
		}
		
		return self::$_instances[$path];
	}
	
	protected function __construct($path)
	{
		$this->SetConfig($path);
	}
	
	protected static function NicePath($path)
	{
		$path = str_replace(array('.', ':', '\\', '~', '"', "'", ' '), '', $path);
		$pathParts = array_values(array_filter(explode('/', $path), 'strlen'));

		if (sizeof($pathParts) < 2) $pathParts[] = 'default';

		$partsNum = sizeof($pathParts);
		while ($partsNum)
		{
	    	$filePath = _APP_PATH. 'config/' .implode('/', $pathParts);
	    	if (Mozg_Storage::Exists($filePath)) break;
	    	
	    	unset($pathParts[--$partsNum]);
		}
		
		if (!$partsNum) throw new Mozg_Exception_System( Mozg_Lang::_('PARAMETERS_FILE_NOT_FOUND', $path));
		
		return implode('/', $pathParts);
	}
	
	protected function SetConfig($path)
	{
		list(, $this->_path) = explode('/', $path, 2);
    	$this->_config = Mozg_Storage::Read(_APP_PATH. 'config/' .$path);

		return $this;
	}

	public function GetPath()
	{
		return $this->_path;
	}

	public function GetConfig()
	{
		return $this->_config;
	}
}
